﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using AlbumDesigner.Helpers;
using Keepo.Models;
using System.IO;
using Keepo.Helpers;

namespace AlbumDesigner.Controllers
{
    [SessionState(SessionStateBehavior.Disabled)] // SessionLess - useful for long actions, to allow other requests to be made at this time
    public class AlbumFilesController : Controller
    {
        public ActionResult ImportImagesFromDirectory(int AlbumId)
        {
            using (AlbumContext db = new AlbumContext())
            {
                var directory = Server.MapPath(@"~/resources/elinirimages");
                var images = new List<AlbumImage>();

                var directoryToSave = Server.MapPath("~/resources/albums/" + AlbumId + "/images");
                var url = "resources/albums/" + AlbumId + "/images";

                if (!Directory.Exists(directoryToSave))
                {
                    Directory.CreateDirectory(directoryToSave);
                }

                if (Directory.Exists(directory))
                {
                    var files = Directory.GetFiles(directory, "*.jpg", SearchOption.TopDirectoryOnly);
                    foreach (var file in files)
                    {
                        var fileName = Guid.NewGuid().ToString().Substring(0, 6) + Path.GetExtension(file);

                        //insert the image to DB as AlbumImage
                        var albumImage = new AlbumImage();
                        albumImage.Title = Path.GetFileNameWithoutExtension(file);
                        albumImage.AlbumId = AlbumId;
                        albumImage.URL = url + "/" + fileName;
                        images.Add(albumImage);

                        System.IO.File.Copy(file, directoryToSave + "\\" + fileName);

                        ImageHelper.addDesignImage(albumImage);
                    }
                }

                db.SaveChanges();
            }

            return Json(true);
        }
    }
}
